package com.itheim.orderservice;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.listener.ReadListener;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheim.orderservice.bean.OrderIdBean;
import com.itheim.orderservice.mapper.OrderExportExcelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;

@Slf4j
@Component
public class ImportExcelListener extends AnalysisEventListener<OrderIdBean> {

    //最大容量
    private static final int MAX_LIST_COUNT = 10000;

    //临时储存
    //private ThreadLocal<ArrayList<OrderIdBean>> threadLocal = ThreadLocal.withInitial(ArrayList::new);
    private ArrayList<OrderIdBean> beans = new ArrayList<>();

    //todo::private static LinkedList<OrderIdBean> orderIdBeans = new LinkedList<>();

    @Autowired
    private OrderExportExcelMapper mapper;

    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(OrderIdBean data, AnalysisContext context) {
        beans.add(data);
        if (beans.size()==MAX_LIST_COUNT){
            save(beans);
        }
    }

    /**
     * 所有数据被解析完毕后
     * 情况:当出现解析完成之后没有达到1000条,比如1万1千条的时候,最后一千条一定要在这里面保存
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        save(beans);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(ArrayList<OrderIdBean> beanArrayList) {
        mapper.addList(beanArrayList);
        this.beans = new ArrayList<>();
        System.out.println();
    }

}
